import datetime
import json
import ssl

from django.db import close_old_connections
from django.db.models import Q

from deviceManage import models as device_m
from deviceManage.views import create_alarm
from logsManage.views import set_server_logs
from roomManage import models as room_m

import paho.mqtt.client as mqtt

from Wchime import settings



mqtthost = settings.mqtthost
mqttport = settings.mqttport
mqttuser = settings.mqttuser
mqttpwd = settings.mqttpassword
mqttTLS = settings.mqttTLS

room_topic = '/room/online'
device_topic = '/device/online'
work_staus_topic = '/work/status'


def room_status_update(uuid, status):
    close_old_connections()
    device = device_m.Device.objects.filter(uuid=uuid).last()
    if device:
        if device.online != status and status == 1:
            device.online = status
            device.status = 1
            device.save()

            room = room_m.RoomMaster.objects.filter(id=device.room_id).last()
            if room:
                room.status = 1
                room.save()
            timer = datetime.datetime.now()
            device_m.Alarm.objects.filter(Q(device_id=device.id) & Q(recovertime=None)).update(
                recovertime=timer
            )
            # print('device go to update online')
        elif device.online != status and status == 0:
            device.online = status
            device.status = 0
            device.save()
            other_devices = device_m.Device.objects.filter(room_id=device.room_id)
            for o_d in other_devices:
                o_d.online = 0
                create_alarm(o_d.id, '离线')
                o_d.save()

            room = room_m.RoomMaster.objects.filter(id=device.room_id).last()
            if room:
                room.status = 0
                room.save()
            # create_alarm(device.id, '离线')
            # print('device go to update offline')
    # room = room_m.RoomMaster.objects.filter(uuid=uuid).last()
    # if room:
    #     if room.status != status and status == 1:
    #         room.status = status
    #         room.save()
    #
    #         print('room go to update online')
    #     elif room.status != status and status == 0:
    #         room.status = status
    #         room.save()
    #         print('room go to update offline')

def device_online_update(uuid, online):
    close_old_connections()
    device = device_m.Device.objects.filter(uuid=uuid).last()
    # print(device)
    if device:
        if device.online != online and online == 1:
            device.online = online
            device.save()
            timer = datetime.datetime.now()
            device_m.Alarm.objects.filter(Q(device_id=device.id) & Q(recovertime=None)).update(
                recovertime=timer
            )
            # print('device go to update online')
        elif device.online != online and online == 0:
            device.online = online
            device.save()
            create_alarm(device.id, '离线')
            # print('device go to update offline')


def device_status_update(uuid, status):
    close_old_connections()
    device = device_m.Device.objects.filter(uuid=uuid).last()
    if device:
        if device.status != status and status == 1:
            device.status = status
            device.save()
            set_server_logs('下发指令', 0, f'发送指令，房间：{device.room.name}设备{device.name} 开始工作', None, None)
            # print('device start work')
        elif device.status != status and status == 0:
            device.status = status
            device.save()
            set_server_logs('下发指令', 0, f'发送指令，房间：{device.room.name}设备{device.name} 停止工作', None, None)
            # print('device stop work')

def msg_process(topic, data):

    data = json.loads(data)
    if topic == room_topic:
        uuid = data.get('uuid')
        status = data.get('status')
        room_status_update(uuid, status)
    elif topic == device_topic:
        uuid = data.get('uuid')
        online = data.get('online')
        device_online_update(uuid, online)
    elif topic == work_staus_topic:
        # print(data)
        uuid = data.get('uuid')
        status = data.get('status')
        device_status_update(uuid, status)




def on_connect(client, userdata, flags, rc):
    print("mqtt连接成功")
    # client.subscribe('/test/')
    client.subscribe(room_topic)
    client.subscribe(device_topic)
    client.subscribe(work_staus_topic)


def on_message(client, userdata, message):
    # print(message.topic, message.payload.decode('utf-8'))
    msg_process(message.topic, message.payload.decode('utf-8'))

def on_subscribe(client, userdata, mid, granted_qos):
    print('mqtt订阅')



def on_disconnect(client, userdata, rc):
    print('mqtt断开')

client = mqtt.Client()
client.on_connect = on_connect

client.on_message = on_message
client.on_subscribe = on_subscribe
client.on_disconnect = on_disconnect
client.username_pw_set(mqttuser, mqttpwd)
if mqttTLS:
    from django.conf import settings as st
    path = st.BASE_DIR + '/tools/wchime.xyz_bundle.crt'
    client.tls_set(path, cert_reqs=ssl.CERT_NONE, tls_version=ssl.PROTOCOL_TLSv1_2)
    client.tls_insecure_set(True)
client.connect_async(host=mqtthost, port=mqttport, keepalive=60, bind_address="")
# client.connect(host='127.0.0.1', port=1883, keepalive=60, bind_address="")
client.loop_start()
